from django.shortcuts import render, redirect
from app01.utils.pagination import Pagination
from app01 import models
from app01.utils.form import UserModelFrom
"""用户管理"""


def user_list(request):
    queryset = models.Userinfo.objects.all()
    # for obj in queryset:
    #     print(obj.id,obj.name,obj.account,obj.create_time.strftime("%Y-%m-%d"),obj.get_gender_display(),obj.depart.title)
    # obj.gender    # 1/2
    # obj.get_gender_display()     # '男'/'女'
    # print(obj.depart_id)   # 获取数据库中存储的那个字段值
    # print(obj.depart)   # 进行连接操作 获取数据库中存储的那个字段值
    page_object = Pagination(request, queryset)
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html()
    }
    return render(request, "user_list.html", context)


"""添加用户原始方法"""


def user_add(request):
    if request.method == "GET":
        content = {
            "gender_choices": models.Userinfo.gender_choices,
            "depart_list": models.Department.objects.all()
        }
        return render(request, "user_add.html", content)
    user = request.POST.get("user")
    pwd = request.POST.get("pwd")
    age = request.POST.get("age")
    account = request.POST.get("account")
    create_date = request.POST.get("create_date")
    gender = request.POST.get("gender")
    depart = request.POST.get("depart")
    print(user, pwd, age, account, create_date, gender, depart)
    models.Userinfo.objects.create(name=user, password=pwd, age=age, account=account, create_time=create_date,
                                   gender=gender, depart_id=depart)
    return redirect("/user/list/")


"""添加用户Model_form方法"""


def user_model_form_add(request):
    """添加用户（ModelFrom版本）"""
    if request.method == "GET":
        form = UserModelFrom()
        return render(request, "user_model_form_add.html", {"form": form})
    # 用户通过POST提交数据，数据校验。
    form = UserModelFrom(data=request.POST)
    if form.is_valid():
        print(form.cleaned_data)
        form.save()
        return redirect("/user/list/")
    # 校验失败（在页面上显示错误信息）
    return render(request, "user_model_form_add.html", {"form": form})


"""编辑用户"""


def user_edit(request, nid):
    row_object = models.Userinfo.objects.filter(id=nid).first()
    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据
        form = UserModelFrom(instance=row_object)
        return render(request, "user_edit.html", {"form": form})
    form = UserModelFrom(data=request.POST, instance=row_object)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据
        # form.instance.字段名 = 值
        form.save()
        return redirect("/user/list/")
    return render(request, "user_edit.html", {"form": form})


def user_delete(request, nid):
    models.Userinfo.objects.filter(id=nid).delete()
    return redirect("/user/list/")

